<?php

namespace pmvc\mvc\controller;

use pmvc\mvc\Controller;
use pmvc\mvc\Request;
use pmvc\mvc\Response;

use Exception;

class ExceptionController
	implements Controller {

	private $showErrorDetails		= true;
	private $preserveOutputBuffer	= true;
	
	/**
	 * {@inheritDoc}
	 */
    public function handleRequest(Request $request, Response $response) {

    	// set the error
    	$response->setStatus(Response::STATUS_INTERNAL_ERROR, "Internal Server Error");

    	// get the exception
    	$ex = $request->getAttribute("exception");
    	$message = ($ex!=NULL) ? $ex->getMessage() : "Unknown";

    	$errorDetails = "";
    	if ($this->showErrorDetails && $ex!=NULL) {
	    	$errorDetails = "Following are the details:
	            </p>
	            <p>
	            	<b>Code</b>: ".$ex->getCode()."<br/>
	            	<b>Message</b>: ".$ex->getMessage()."<br/>
	            	<b>File</b>: ".$ex->getFile()."<br/>
	            	<b>Line</b>: ".$ex->getLine()."<br/>
	            	<b>Trace</b>:<br><pre>".$ex->getTraceAsString()."</pre><br/>";
    	}

    	if (!$this->preserveOutputBuffer) {
    		$response->reset();
    	}
    	
    	$response->getStream()->write("
	    	<html>
	    	    <head>
	    	        <title>Internal Server Error: ".$message."</title>
	    	    </head>
		        <body>
		            <h1>An error occured while handling your request.</h1>
		            <p>
		                The page that you have requested (".$request->getRequestedUrl().")
		                has resulted in an error. ".$errorDetails."
		            </p>
		        </body>
	    	</html>
    	");
    }

    public function setShowErrorDetails($showErrorDetails) {
    	$this->showErrorDetails = $showErrorDetails;
    }

    public function setPreserveOutputBuffer($preserveOutputBuffer) {
    	$this->preserveOutputBuffer = $preserveOutputBuffer;
    }
	
}

?>